<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Museumslogs;
use app\common\model\Museumsthird;
use app\common\model\user\Appoints;
use app\common\model\UserCards;
use app\common\model\UserPunch;
use fast\Random;
use think\Log;

class Login  extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function checklogins()
    {
        $code = $this->request->param("code");
        $from = $this->request->param("from", "");
        $data_id = $this->request->param("data_id", 0);
        if (!$code) {
            $this->error("参数不正确");
        }
        if($this->auth->isLogin()){
            $this->success('',4);
        }
        $is_login = $this->request->param("is_login",0);

        $wxmini=new \app\common\library\Wxmini();
        $json=$wxmini->jscode2session($code);
        $userThirdModel=new \app\common\model\UserThird;
        $userModel=new \app\common\model\User;

        if (isset($json['openid'])) {

            $third=$userThirdModel->where('platform','wx')->where('apptype',1)->getByOpenid($json['openid']);
            if (!empty($from) && !empty($data_id) && empty($third)) {
                $user = $userModel->where('id',$data_id)->find();
                if (!empty($user) && empty($third)) {
                    $saveData=[
                        'nickname'       => $user->nickname,
                        'avatar'         => $user->avatar,
                        'gender'         => $user->gender,
                        'user_id'         => $user->id,
                        'platform'       => 'wx',
                        'apptype'        => 1,
                        'unionid'        => isset($json['unionid'])?$json['unionid']:'',
                        'openid'         => isset($json['openid'])?$json['openid']:'',
                        'access_token'   => isset($json['session_key'])?$json['session_key']:'',
                        'expires_in'     => 0,
                        'createtime'   => time(),
                        'updatetime'   => time()
                    ];
                    $nowTime=time();
                    $saveData['expiretime']=$nowTime + $saveData['expires_in'];
                    if (!empty($user->mobile)) {
                        $saveData['authorization_status'] = 3;
                    }
                    $ins_res = $userThirdModel->save($saveData);
                    if ($ins_res) {
                        $third=$userThirdModel->where('platform','wx')->where('apptype',1)->getByOpenid($json['openid']);
                    } else {
                        $this->error('用户信息不存在');
                    }
                }
            } else {
                $user = $userModel->where('id',isset($third['user_id'])?$third['user_id']:0)->find();
            }
            if($third&&$user&&$third['user_id']>0){
                // 判断是否存在该用户
                if ($user->status != 'normal') {
                    $this->error('您已被拉黑');
                }
                //如果已经有账号则直接登录

                if (empty($from)) {
                    $this->success('',3);
                } else {
                    $ret = $this->auth->direct($user->id);
                    if ($ret) {

                        $data = ['need_login_type'=>1,'authorization_status'=>3,'openid'=>$json['openid'],
                            'userinfo' => \app\common\model\User::getmine(['id'=>$this->auth->id])];
                        $data['userinfo']['token']=$this->auth->getUserInfo()['token'];
                        $this->success('', $data);
                    } else {
                        $this->error($this->auth->getError());
                    }
                }

            }else{
                if($third){
                    if(empty($user['authorization_status'])==2){
                        $this->success('',2);
                    }else{
                        $this->success('',2);
                    }
                } else {
                    $this->error('用户数据不存在');
                }
            }
        }
    }
    /**
     * 会员中心
     */
    public function index()
    {
        try {
            $this->success('', \app\common\model\User::getmine(['id'=>$this->auth->id]));
        } catch (\think\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    public function getMorders()
    {
        $data['appoints']=0;
        $data['benefits']=0;
        if($this->auth->isLogin()){
            $data['appoints']=Appoints::where(['user_id'=>$this->auth->id,'status'=>0])->count();
            $data['benefits']=UserCards::where(['user_id'=>$this->auth->id,'can_uses'=>['>',0],'status'=>1])->count();
        }
        $this->success('',$data);
    }

    /**
     * 是否登录
     */
    public function checkLogin()
    {
        $data['login'] =$this->auth->isLogin();
        $this->success('',$data);
    }
    public function userLogin($code)
    {
        $code = $this->request->param("code");
        if (!$code) {
            $this->error("参数不正确");
        }
        $is_login = $this->request->param("is_login",0);

        $wxmini=new \app\common\library\Wxmini();
        $json=$wxmini->jscode2session($code);

        $saveData=[
            'platform'       => 'wx',
            'apptype'        => 1,
            'unionid'        => isset($json['unionid'])?$json['unionid']:'',
            'openid'         => isset($json['openid'])?$json['openid']:'',
            'access_token'   => isset($json['session_key'])?$json['session_key']:'',
            'expires_in'     => 0,
        ];
        $nowTime=time();
        $saveData['expiretime']=$nowTime + $saveData['expires_in'];
        $userModel=new \app\common\model\User;
        $userThirdModel=new \app\common\model\UserThird;
        $authorization_status =1;
        if (isset($json['openid'])) {
            // 判断第三方登录表里是否存在该数据
            $third=$userThirdModel->where('platform','wx')
                ->where('apptype',1)->getByOpenid($json['openid']);
            $user = $userModel->where('id',isset($third['user_id'])?$third['user_id']:0)->find();
            if($third&&$user&&$third['user_id']>0&&$is_login==0){
                // 判断是否存在该用户
                if ($user->status != 'normal') {
                    $this->error('您已被拉黑');
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
                if ($ret) {

                    $data = ['need_login_type'=>1,'authorization_status'=>3,'openid'=>$saveData['openid'],'userinfo' => \app\common\model\User::getmine(['id'=>$this->auth->id])];
                    $data['userinfo']['token']=$this->auth->getUserInfo()['token'];
                    $this->success('登录成功', $data);
                } else {
                    $this->error($this->auth->getError());
                }
            }else{
                if($third){

                    $third->save($saveData);
                    if($third['authorization_status']==2){
                        $authorization_status=2;
                    }
                }else{
                    $userThirdModel->save($saveData);
                }
            }
            $this->success('', ['need_login_type'=>2,'openid'=>$saveData['openid'],'authorization_status'=>$authorization_status]);
        } else {
            $this->error("登录失败");
        };
    }

    public function getUserMessage()
    {
        $post = $this->request->param();
        $post['userInfo']=changetype($post['userInfo']);
        if(!isset($post['openid'])||!$post['openid']){
            $this->error('参数错误');
        }
        if(!isset($post['userInfo'])||!$post['userInfo']){
            $this->error('参数错误');
        }
        $userInfo=$post['userInfo'];
        $userThirdModel=new \app\common\model\UserThird;
        $thirdInfo=$userThirdModel->where('platform','wx')->where('apptype',1)->where('openid',$post['openid'])->find();
        $post['session_key']=$thirdInfo['access_token'];
        $save_Data=[
            'nickname'=>isset($userInfo['nickName'])?$userInfo['nickName']:'',
            'avatar'=>isset($userInfo['avatarUrl'])?$userInfo['avatarUrl']:'',
            'authorization_status'=>2];
        $thirdInfo->save($save_Data);
        $this->success('',$thirdInfo);
    }

    /**
     * 获取手机号
     */
    public function getPhone()
    {
        $post = $this->request->param();
        if(!isset($post['openid'])||!$post['openid']){
            $this->error('参数错误');
        }
        $userThirdModel=new \app\common\model\UserThird;
        $thirdInfo=$userThirdModel->where('platform','wx')->where('apptype',1)->where('openid',$post['openid'])->find();
        $post['session_key']=$thirdInfo['access_token'];
        $res=$userThirdModel->decryptPhoneNumber($post);
        if(!$res['status']){
            $this->error($res['info']);
        }
        $mobile =$res['data']['mobile'];
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if($user&&$thirdInfo['user_id']!=$user['id']){
            $this->error(__('该手机号已绑定其他微信号'));
        }
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, [
                'nickname'=>$thirdInfo['nickname'],
                'avatar'=>$thirdInfo['avatar'],
                'openid'=>$thirdInfo['openid'],
                'money'=>0,
                'rec_uid'=>isset($post['rec_uid'])?$post['rec_uid']:0,
            ]);

        }
        if ($ret) {
            $thirdInfo->save(['user_id'=>$this->auth->id]);
            $data = ['userinfo' => \app\common\model\User::getmine(['id'=>$this->auth->id])];
            $data['userinfo']['token']=$this->auth->getUserInfo()['token'];
            // 绑定用户id

            $this->success('登录成功', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
}